#!/bin/bash
# - qcow2_os
# - qcow2_arch
# - qcow2_version
# - qcow2_url
# - rootfs_dir
# - rootfs_protocol
# - rootfs_server
# - rootfs_path

umask 0002

. $LKP_SRC/lib/env.sh
. $LKP_SRC/lib/log.sh

check_yaml_vars()
{
	log_info "starting check yaml vars ..."

	local yaml_vars=(
		"qcow2_os"
		"qcow2_arch"
		"qcow2_version"
		"rootfs_protocol"
		"rootfs_server"
		"rootfs_path"
	)

	for yaml_t in "${yaml_vars[@]}"
	do
		[ -n "$(eval echo "\$${yaml_t}")" ] || die "cannot find value of var: ${yaml_t}."
	done
}

set_qcow2rootfs_tools()
{
        export QCOW2_PATH="/c/compass-ci/container/qcow2rootfs"
        export CCI_SRC="/c/compass-ci"
        [ -d "$CCI_SRC" ] || {
                git clone https://gitee.com/Ethan-Zhang/compass-ci.git /c/compass-ci
        }
        rm ${QCOW2_PATH}/root/$(arch)/etc/yum.repos.d/*
	wget -O ${QCOW2_PATH}/root/$(arch)/etc/yum.repos.d/CentOS-Base.repo https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/repo/$(arch)/CentOS-Base.repo

        mkdir -p /etc/systemd/system/docker.service.d
        cat >/etc/systemd/system/docker.service.d/10-ramdisk.conf << EOF
        [Service]
        Environment=DOCKER_RAMDISK=true
EOF

        systemctl daemon-reload
        systemctl restart docker

        cd ${QCOW2_PATH}
        ./build || {
                echo "build container failed~"
                wget -O qcow2rootfs:auto.tar https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/qcow2rootfs:auto.tar
		load_and_tag_image "qcow2rootfs:auto.tar" "qcow2rootfs:auto"
        }
        sed -i 's#$EXTRACT_ROOT/bin/extract $QCOW2_FILE $tar_out_file#$EXTRACT_ROOT/bin/extract $EXTRACT_ROOT/qcow2-dir/$QCOW2_NAME $tar_out_file#' \
                ${QCOW2_PATH}/bin/main

}

check_url()
{
	export QCOW2_NAME="${qcow2_os}-${qcow2_version}-${qcow2_arch}.qcow2"

	[ -n "$qcow2_url" ] && [[ "$qcow2_url" =~ .qcow2$ || "$qcow2_url" =~ .qcow2.xz$ ]] && {
                export QCOW2_URL="$qcow2_url"

	        qcow2_filetype="${qcow2_url##*.}"
	
		if [ "${qcow2_filetype}" == "xz" ];then
            	        export QCOW2_NAME="${QCOW2_NAME}.xz"
	        fi
	} || {
		die "The URL of the qcow2 file is not given."
	}
}

load_and_tag_image()
{
        local tar_file="$1"
	local image_tag="$2"

	output=$(docker load -i "$tar_file")
	image_id=$(echo "$output" | awk '/Loaded image ID:/ {print substr($4, 8)}')
        docker tag "$image_id" "$image_tag"

	echo "The image has been loaded and tagged as $image_tag"
}

download_qcow2_img()
{
	mkdir -p ${IMG_PATH} && cd ${IMG_PATH}
	[ -f "${IMG_PATH}/${QCOW2_NAME}" ] || {
		wget -O $QCOW2_NAME ${QCOW2_URL} || exit 1
	}
}

mount_os_rw()
{
        [ -n "$ROOTFS_DIR" ] && {
		export ROOTFS_PATH="${MOUNT_POINT}/openeuler/${qcow2_arch}/${qcow2_version}-${ROOTFS_DIR}"
	} || {
		export ROOTFS_PATH="${MOUNT_POINT}/openeuler/${qcow2_arch}/${qcow2_version}"
	}

	[ -d "$ROOTFS_PATH" ] && {
		if [ "`ls -A $ROOTFS_PATH`" = "" ];then
			echo "$ROOTFS_PATH is indeed empty"
		else
			umount ${MOUNT_POINT}
			echo $ROOTFS_PATH
			exit 0
		fi
	}
}

mount_initramfs()
{
	export INITRD_MOUNT_POINT="${IMG_PATH}/initrd"
        mkdir -p ${INITRD_MOUNT_POINT}
        mount -t ${rootfs_protocol} -o rw ${rootfs_server}:/initrd ${INITRD_MOUNT_POINT}

	export INITRD_ROOTFS_PATH="${INITRD_MOUNT_POINT}/osimage/openeuler/${qcow2_arch}/${qcow2_version}"
}

extract_rootfs()
{
	mkdir -p $ROOTFS_PATH
	wget -O debian:dracut.tar https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/debian:dracut.tar
        load_and_tag_image "debian:dracut.tar" "debian:dracut"

	cd ${QCOW2_PATH}
	./run ${IMG_PATH}/${QCOW2_NAME} ${ROOTFS_PATH}
}

set_resolv_config()
{
	cat >${ROOTFS_PATH}/etc/resolv.conf<<-EOF
	nameserver 114.114.114.114
	EOF
}

set_link()
{
	cd ${MOUNT_POINT}/openeuler/${qcow2_arch}
        [ -n "$ROOTFS_DIR" ] && {
	        if [ "${ROOTFS_DIR##rc*}" != "${ROOTFS_DIR}" ]; then
	        	rc_version=${ROOTFS_DIR%%_openeuler*}
	        	ln -fsT ${qcow2_version}-${ROOTFS_DIR} ${qcow2_version}-$rc_version-iso
	        	ln -fsT ${qcow2_version}-${ROOTFS_DIR} ${qcow2_version}-$rc_version
	        elif [ "${ROOTFS_DIR##test*}" != "${ROOTFS_DIR}" ]; then
	        	rc_version=${ROOTFS_DIR%%_openeuler*}
	        	ln -fsT ${qcow2_version}-${ROOTFS_DIR} ${qcow2_version}-$rc_version-iso
	        	ln -fsT ${qcow2_version}-${ROOTFS_DIR} ${qcow2_version}-$rc_version
	        else
	        	ln -fsT ${qcow2_version}-${ROOTFS_DIR} ${qcow2_version}-dailybuild-iso
	        	ln -fsT ${qcow2_version}-${ROOTFS_DIR} ${qcow2_version}-dailybuild
	        fi
        } || {
                ln -fsT ${qcow2_version} ${qcow2_version}-iso
        }
	echo $ROOTFS_PATH
}

create_initramfs()
{
	target_dir="${ROOTFS_PATH}-tmp"

	# Check if the directory exists, and create it if it doesn't
	if [ ! -d "$target_dir" ]; then
		mkdir -p "$target_dir"
	fi
	
	# Synchronize root file system
	rsync -a "$ROOTFS_PATH/." "$target_dir/"

	cd "$target_dir"
	rm -rf lib/modules/* boot/vmlinuz* boot/initr*

	if [ ! -d "$INITRD_ROOTFS_PATH" ]; then
		mkdir -p "$INITRD_ROOTFS_PATH"
	fi
	initramfs_cgz="$INITRD_ROOTFS_PATH/$(date +"%Y%m%d").0.cgz"

	# Create initramfs
	find . | cpio -o -Hnewc | gzip -9 > "$initramfs_cgz"
	
	# Navigate to INITRD_ROOTFS_PATH
	cd "$INITRD_ROOTFS_PATH"
	
	# Create symbolic links
	ln -sf "$(basename "$initramfs_cgz")" current
	ln -sf ../../../../deps/nfs/debian/aarch64/sid/run-ipconfig.cgz run-ipconfig.cgz
	
	# Cleanup
	rm -rf "$target_dir"

	echo "Initramfs rootfs has been created successfully."
}

set_mount_point()
{
	export IMG_PATH="/root/qcow2"
	export MOUNT_POINT="${IMG_PATH}/mnt"
	mkdir -p ${MOUNT_POINT}
	mount -t ${rootfs_protocol} -o rw ${rootfs_server}:/${rootfs_path} ${MOUNT_POINT}

	export ROOTFS_DIR="$rootfs_dir"
}

umount_rootfs()
{
	umount ${MOUNT_POINT}
	umount ${INITRD_MOUNT_POINT}
}

set_mount_point
mount_os_rw
check_yaml_vars
set_qcow2rootfs_tools
check_url
download_qcow2_img
extract_rootfs
set_resolv_config
set_link
mount_initramfs
create_initramfs
umount_rootfs
